package com.orange.cloud.common.core.web.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.orange.cloud.common.core.constant.AuthConstants;
import com.orange.cloud.common.core.feign.user.pojo.dto.UserDTO;
import com.nimbusds.jose.JWSObject;
import org.apache.logging.log4j.util.Strings;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

/**
 * @Authoer Administrator
 * @Descrption 获取当前token对应的用户ID
 * @Date 2021/2/18 18:25
 */
public class LoginUserUtils {

    public static UserDTO getCurrentUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(AuthConstants.JWT_TOKEN_HEADER);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        // 解析JWT获取jti，以jti为key判断redis的黑名单列表是否存在，存在拦截响应token失效
        token = token.replace(AuthConstants.JWT_TOKEN_PREFIX, Strings.EMPTY);
        JWSObject jwsObject = null;
        try {
            jwsObject = JWSObject.parse(token);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;

        }
        String payload = jwsObject.getPayload().toString();
        JSONObject jsonObject = JSONUtil.parseObj(payload);
        return JSONUtil.toBean(jsonObject, UserDTO.class);
//        return jsonObject.getLong(AuthConstants.JWT_USER_ID_KEY);
    }


}
